<?php
class ReviewController extends AppController {
	function beforeFilter () {
		parent::beforeFilter();
		$this->CustomAuth->allow('index');
	}
	function index($courseId) {
		$this->loadModel('Course');

		$userId = 0;
		if ($user = $this->CustomAuth->user()) {
			$userId = $user['User']['id'];
		}

		if (!$this->Session->check('Admin.isLogin') || !$this->Session->read('Admin.isLogin')) {
			$options['conditions'] = array(
				$this->Course->alias . '.del_flg' => 0,
				'OR' => array(
					$this->Course->alias . '.display_flg' => 1,
					$this->Course->alias . '.user_id' => $userId,
				)
			);
		}
		$options['conditions'][$this->Course->alias . '.' . $this->Course->primaryKey] = $courseId;

		$course = $this->Course->getForView($options);

		if (!$course) {
			$this->cakeError('error404');
		}
		if (isset($this->params['url']['detail']) && $detailId = $this->params['url']['detail']) {
			$detail = $this->Course->getCourseDetail($courseId, $detailId);
		}
		if (!isset($detail) || !$detail) {
			$details = $this->Course->getClosestCourseDetail($courseId);
			$detail = array();
			if (isset($details[$courseId])) {
				$detail = $details[$courseId];
			}
		}
		$this->loadModel('CourseDetail');
		//check if joined to a course detail
		$this->loadModel('EnteredCourse');
		$this->loadModel('TargetOfWatch');
		$isJoined = false;
		$isFull = false;
		if ($detail) {
			$isJoined = $this->EnteredCourse->isEnteredCourse($detail['CourseDetail']['id'], $userId);
			$isFull = $this->CourseDetail->isFull($detail['CourseDetail']['id']);
		}

		$exclusiveIds = array($course['Course']['id']);

		$userCourses = $this->Course->getRelatedByUser($course['Course']['user_id'], $exclusiveIds);

		$exclusiveIds = array_merge($exclusiveIds, array_keys($userCourses));
		$categoryCourses = $this->Course->getRelatedByCategory($course['Course']['category'], $exclusiveIds);

		$exclusiveIds = array_merge($exclusiveIds, array_keys($categoryCourses));
		$areaCourses = $this->Course->getRelatedByArea($course['Course']['area'], $exclusiveIds);

		$this->loadModel('Tag');
		$watchListInfo = $this->TargetOfWatch->getTargetOfWatchInformationByUserIdAndTeacherId($this->CustomAuth->user('id'), $course['Course']['user_id']);

		$options = array(
			'conditions' => array(
				$this->Review->alias . '.course_id' => $courseId,
				$this->Review->alias . '.del_flg' => 0,
			)
		);
		$this->paginate = $this->Review->getList($options, true);
		$this->paginate['limit'] = Configure::read('page_limit');
		$this->set(array(
			'course' => $course,
			'detail' => $detail,
			'areaCourses' => $areaCourses,
			'tags' => $this->Tag->getTagByCourse($courseId),
			'categoryCourses' => $categoryCourses,
			'userCourses' => $userCourses,
			'isJoined' => $isJoined,
			'isFull' => $isFull,
			'watchListInfo' => $watchListInfo,
			'reviews' => $this->paginate('Review'),
		));
	}

	function add() {
		if ($this->RequestHandler->isAjax()) {
			$this->data['user_id'] = $this->CustomAuth->user('id');
			$this->loadModel('Course');
			$isOwner = $this->Course->isOwner($this->data['course_id'], $this->data['user_id']);
			if ($isOwner) {
				$result = array(
					'status' => false,
					'data' => array (
						'message' => Messages::you_could_not_post_review_for_this_course
					)
				);
				$this->set('json', $result);
				return $this->render('/elements/json', 'ajax');
			} else {
				if ($this->Course->isJoined($this->data['course_id'], $this->data['user_id'])) {
					$this->data['user_type'] = Review::USER_TYPE_JOINED;
				} else {
					$result = array(
						'status' => false,
						'data' => array (
							'message' => Messages::you_could_not_post_review_for_this_course
						)
					);
					$this->set('json', $result);
					return $this->render('/elements/json', 'ajax');
				}
			}
			if ($review = $this->Review->add($this->data)) {
				$review['Review']['id'] = $this->Review->id;
				$review['Profile']['first_name'] = $this->Session->read('User.name');
				$review['Profile']['icon_image'] = $this->Session->read('User.icon_image');
				$this->set('review', $review);
				$html = $this->render('/elements/review/item', 'ajax');
				$result = array(
					'status' => true,
					'data' => array(
						'html' => $html,
					)
				);
				$this->output = ''; //reset output
				$this->_updateUserCourseStatus($review['Review']['course_id']);
				$this->set('json', $result);
			} else {
				$result = array(
					'status' => false,
					'data' => array (
						'message' => Messages::there_some_problem_please_try_later
					)
				);
				$this->set('json', $result);
			}
			return $this->render('/elements/json', 'ajax');
		} else {
			if (isset ($this->params['url']['id']) && $id = $this->params['url']['id']) {
				$this->redirect(array('controller' => 'course', 'action' => 'view', $id));
			} else {
				$this->cakeError('error404');
			}
		}
	}

	function delete() {
		$reviewId = $this->data['id'];
		$userId = $this->CustomAuth->user('id');
		$status = $this->Review->updateDelFlg($reviewId, $userId);

		if ($this->RequestHandler->isAjax()) {
			if ($status) {
				$result = array(
					'status' => true,
					'data' => array(
						'id' => $reviewId,
					)
				);
			} else {
				$result = array(
					'status' => false,
					'data' => array(
						'message' => Messages::you_could_not_delete_this_review,
					)
				);
			}
			$this->set('json', $result);
			return $this->render('/elements/json', 'ajax');
		} else {
			$this->redirect($this->referer());
		}
	}

	function _updateUserCourseStatus($courseId) {
		$courses = $this->Session->read('User.pass_courses');
		if (isset($courses[$courseId])) {
			unset($courses[$courseId]);
		}
		$this->Session->write('User.pass_courses', $courses);
	}
}